package com.jinunn.msm.controller;

import com.jinunn.common.result.Result;
import com.jinunn.msm.service.MsmService;
import com.jinunn.msm.utils.RandomUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author JinDun
 * @date 2021/5/13 0:07
 */
@RestController
@RequestMapping("/msm")
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @GetMapping("/send/{phone}")
    public Result sendCode(@PathVariable("phone") String phone){
        //从redis获取验证码，如果不为null,就返回ok
        String code = redisTemplate.opsForValue().get(phone);
        if (StringUtils.isNotBlank(code)){
            return Result.ok();
        }
        //如果获取不到
        //生成6位数的验证码
        code = RandomUtil.getSixBitRandom();
        //调用方法，通过整合短信服务发送短信。
       Boolean isSend = msmService.send(code,phone);
       //如果返回为true,把生成的验证码放入到redis中，并设置有效时间。
       if (isSend){
           redisTemplate.opsForValue().set(phone,code,20, TimeUnit.MINUTES);
           return Result.ok();
       }else {
           return Result.fail().message("发送短信失败！");
       }
    }

}
